import { Card, Checkbox, Form, Select, SelectProps } from 'antd';
import {
  ProForm,
  ProFormCheckbox,
  ProFormInstance,
  ProFormSelect,
  ProFormText,
  ProFormTimePicker,
} from '@ant-design/pro-components';
import { Col, Row, Space, message } from 'antd';
import { getRoomsConfigView, postRoomsConfigEdit } from './request';
import { useRef, useState } from 'react';
import { CheckboxChangeEvent } from 'antd/es/checkbox';
import { useIntl } from '@umijs/max';

const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

const CardPermissions: React.FC = () => {
  const formRef = useRef<ProFormInstance>();
  const formItemLayout = {
    labelCol: { span: 3 },
    wrapperCol: { span: 14 },
  };

  const options: SelectProps['options'] = [];
  for (let i = 1; i < 61; i++) {
    const value = `${i}`;
    options.push({
      label: value,
      value,
    });
  }

  const intl = useIntl();

  const [id, setID] = useState(0);

  // 直接退房变干净房
  const [defaultCheckoutConfig, setDefaultCheckoutConfig] = useState(false);
  // 保存旧的直接退房状态---以作重置内容
  const [oldDefaultCheckoutConfig, setOldDefaultCheckoutConfig] = useState(false);

  // 选择相应时间变干净房
  const [selectValue, setSelectValue] = useState<number | null>(null);
  // 保存旧的相应时间内容--以作重置内容
  const [oldSelectValue, setOldSelectValue] = useState<number | null>(null);

  // 将证件号保存起来
  const [defaultCheckInIdCard, setDefaultCheckInIdCard] = useState();

  // 相应时间发生变化
  const handleChange = (value: number) => {
    setSelectValue(value);
  };

  // 变干净房发生变化
  const checkChange = (e: CheckboxChangeEvent) => {
    setDefaultCheckoutConfig(e.target.checked);
    setSelectValue(null);
  };

  return (
    <Card
      title={intl.formatMessage({ id: 'RoomSettings.Room Settings Card' })}
      style={{ height: '90vh' }}
    >
      <ProForm
        {...formItemLayout}
        layout={'horizontal'}
        formRef={formRef}
        submitter={{
          render: (props, doms) => {
            return (
              <>
                {' '}
                <Row>
                  <Col span={5} offset={4}>
                    <Space>{doms}</Space>
                  </Col>
                </Row>
              </>
            );
          },
          searchConfig: {
            submitText: intl.formatMessage({ id: 'SetUser.Save' }),
          },
        }}
        onReset={() => {
          // 重置表单内容
          setDefaultCheckoutConfig(oldDefaultCheckoutConfig);
          setSelectValue(oldSelectValue);
          formRef.current?.getFieldsValue();
        }}
        onFinish={async (values) => {
          await waitTime(500);

          let defaultCardT6TimeoutFalseLockAlarm = values.checkbox.includes('a1') ? 1 : 0;
          let defaultCardT8LockedAlarm = values.checkbox.includes('a2') ? 1 : 0;
          let defaultCardT7MuteAlarm = values.checkbox.includes('a3') ? 1 : 0;
          // let defaultCardOverwrite = values.checkbox.includes('a4') ? 1 : 0;

          const res: any = await postRoomsConfigEdit({
            ...values,
            defaultCheckInIdCard,
            defaultCardT6TimeoutFalseLockAlarm,
            defaultCardT8LockedAlarm,
            defaultCardT7MuteAlarm,
            id,
            defaultCheckoutConfig: defaultCheckoutConfig === true ? 0 : selectValue,
          });
          if (res.code !== 0) return message.error(res.msg);
          message.success(res.msg);
          await waitTime(500);
          // window.location.reload();
          return;
        }}
        request={async () => {
          await waitTime(100);
          const res = await getRoomsConfigView();

          setDefaultCheckInIdCard(res.data.defaultCheckInIdCard);

          const one = res.data.defaultCardT6TimeoutFalseLockAlarm;
          const two = res.data.defaultCardT8LockedAlarm;
          const three = res.data.defaultCardT7MuteAlarm;
          // const four = res.data.defaultCardOverwrite;

          setDefaultCheckoutConfig(res.data.defaultCheckoutConfig === 0 ? true : false);
          setSelectValue(
            res.data.defaultCheckoutConfig > 0 ? res.data.defaultCheckoutConfig : null,
          );
          setID(res.data.id);

          setOldSelectValue(
            res.data.defaultCheckoutConfig > 0 ? res.data.defaultCheckoutConfig : null,
          );
          setOldDefaultCheckoutConfig(res.data.defaultCheckoutConfig === 0 ? true : false);

          return {
            defaultCheckInPeople: res.data.defaultCheckInPeople,
            defaultCheckInMobile: res.data.defaultCheckInMobile,
            // defaultCheckInIdCard: res.data.defaultCheckInIdCard,
            defaultCheckoutTime: res.data.defaultCheckoutTime,
            defaultCheckinDay: res.data.defaultCheckinDay,
            defaultCheckInSource: res.data.defaultCheckInSource,
            checkbox: [one ? 'a1' : '', two ? 'a2' : '', three ? 'a3' : ''],
            defaultHourlyRoomTime: res.data.defaultHourlyRoomTime,
          };
        }}
      >
        <ProFormTimePicker
          width="md"
          name="defaultCheckoutTime"
          label={intl.formatMessage({ id: 'SetUser.Default checkout time' })}
          allowClear={false}
        />
        <ProFormSelect
          width={'md'}
          name="defaultCheckinDay"
          label={intl.formatMessage({ id: 'SetUser.Default checkin day' })}
          request={async () => [
            { label: 1 + intl.formatMessage({ id: 'SetUser.Day' }), value: 1 },
            { label: 2 + intl.formatMessage({ id: 'SetUser.Day' }), value: 2 },
            { label: 3 + intl.formatMessage({ id: 'SetUser.Day' }), value: 3 },
            { label: 4 + intl.formatMessage({ id: 'SetUser.Day' }), value: 4 },
            { label: 5 + intl.formatMessage({ id: 'SetUser.Day' }), value: 5 },
          ]}
          allowClear={false}
        />
        <ProFormSelect
          width={'md'}
          name="defaultHourlyRoomTime"
          label={intl.formatMessage({ id: 'SetUser.Default hourly room time' })}
          request={async () => [
            { label: 1 + intl.formatMessage({ id: 'SetUser.Hour' }), value: 1 },
            { label: 2 + intl.formatMessage({ id: 'SetUser.Hour' }), value: 2 },
            { label: 3 + intl.formatMessage({ id: 'SetUser.Hour' }), value: 3 },
            { label: 4 + intl.formatMessage({ id: 'SetUser.Hour' }), value: 4 },
            { label: 5 + intl.formatMessage({ id: 'SetUser.Hour' }), value: 5 },
          ]}
          allowClear={false}
        />
        <Form.Item label={intl.formatMessage({ id: 'SetUser.Default checkout config' })}>
          <div>
            <Checkbox onChange={checkChange} checked={defaultCheckoutConfig}>
              {intl.formatMessage({ id: 'SetUser.Clean the room up.' })}
            </Checkbox>
          </div>
          &emsp;
          <div>
            <Select
              value={selectValue}
              disabled={Number(defaultCheckoutConfig) < 1 ? false : true}
              style={{ width: 60 }}
              onChange={handleChange}
              options={options}
              allowClear={false}
            />
            &nbsp; {intl.formatMessage({ id: 'SetUser.Clean the room up.' })}
          </div>
        </Form.Item>
        <ProFormCheckbox.Group
          name="checkbox"
          label={intl.formatMessage({ id: 'SetUser.Default room card config' })}
          layout={'vertical'}
          options={[
            { label: intl.formatMessage({ id: 'SetUser.Overtime alarm' }), value: 'a1' },
            { label: intl.formatMessage({ id: 'SetUser.Deadbolt' }), value: 'a2' },
            { label: intl.formatMessage({ id: 'SetUser.Silence' }), value: 'a3' },
            // { label: '覆盖已写客人卡', value: 'a4' },
          ]}
        />
        <ProFormSelect
          width={'md'}
          name="defaultCheckInSource"
          label={intl.formatMessage({ id: 'SetUser.Source of Guests' })}
          request={async () => [
            {
              label: intl.formatMessage({ id: 'SetUser.Arrived at the store' }),
              value: intl.formatMessage({ id: 'SetUser.Arrived at the store' }),
            },
            {
              label: intl.formatMessage({ id: 'SetUser.Fliggy' }),
              value: intl.formatMessage({ id: 'SetUser.Fliggy' }),
            },
            {
              label: intl.formatMessage({ id: 'SetUser.Ctrip' }),
              value: intl.formatMessage({ id: 'SetUser.Ctrip' }),
            },
            {
              label: intl.formatMessage({ id: 'SetUser.Qunar' }),
              value: intl.formatMessage({ id: 'SetUser.Qunar' }),
            },
            {
              label: intl.formatMessage({ id: 'SetUser.AliPay' }),
              value: intl.formatMessage({ id: 'SetUser.AliPay' }),
            },
            {
              label: intl.formatMessage({ id: 'SetUser.Others' }),
              value: intl.formatMessage({ id: 'SetUser.Others' }),
            },
          ]}
          allowClear={false}
        />
        <ProFormText
          width="md"
          name="defaultCheckInPeople"
          label={intl.formatMessage({ id: 'SetUser.Guest Name' })}
          allowClear={false}
        />
        <ProFormText
          width="md"
          name="defaultCheckInMobile"
          label={intl.formatMessage({ id: 'SetUser.Mobile' })}
          allowClear={false}
          rules={[
            {
              pattern: new RegExp(
                // eslint-disable-next-line no-useless-escape
                // 11位的数字就能通过校验
                '^\\d{11}$',
              ),
              message: intl.formatMessage({ id: 'SetUser.Please mobile' }),
            },
          ]}
        />
        {/* <ProFormText width="md" name="defaultCheckInIdCard" label="证件号" /> */}
      </ProForm>
    </Card>
  );
};

export default CardPermissions;
